﻿using UnityEngine;  
using System.Collections;  
using System.Collections.Generic;  
using UnityEditor;  

//使用前最好先锁定Inspector面板！  
[CustomEditor(typeof(CustomMesh))]    
public class CustomMeshEditor : Editor {  
	
	private List<Vector3> vertices = new List<Vector3>();  
	private int[] triangles;  
	
	void OnSceneGUI()  
	{  
		CustomMesh customMesh = (CustomMesh)target;  
		
		for (int i = 0; i < vertices.Count; i++)  
		{  
			Handles.PositionHandle(vertices[i], Quaternion.identity);  
			Handles.Label(vertices[i], i.ToString());  
		}  
		if (vertices.Count > 1)  
		{  
			Handles.DrawPolyLine(vertices.ToArray());  
			Handles.DrawLine(vertices[vertices.Count - 1], vertices[0]);  
		}       
		
		//在OnSceneGUI()中只能通过Handles来绘制新视图  
		//如果你想引入GUI的元素哪么就需要使用BeginGUI()和EndGUI()组合的使用。    
		Handles.BeginGUI();  
		GUILayout.BeginArea(new Rect(0, 0, 100, 100));  
		
		if (GUILayout.Button("创建点"))  
		{  
			vertices.Add(customMesh.transform.position);            
		}  
		if (GUILayout.Button("撤销点"))  
		{  
			vertices.RemoveAt(vertices.Count - 1);  
		}  
		if (GUILayout.Button("导出mesh"))  
		{  
			Mesh mesh = new Mesh();  
			
			int triangleAmount = vertices.Count - 2;  
			triangles = new int[3 * triangleAmount];  
			
			//根据三角形的个数，来计算绘制三角形的顶点顺序（索引）  
			//顺序必须为顺时针或者逆时针  
			for (int i = 0; i < triangleAmount; i++)  
			{  
				triangles[3 * i] = 0;//固定第一个点  
				triangles[3 * i + 1] = i + 1;  
				triangles[3 * i + 2] = i + 2;  
			}  
			
			mesh.vertices = vertices.ToArray();  
			mesh.triangles = triangles;  
			
			AssetDatabase.CreateAsset(mesh, "Assets/CustomMesh.asset");  
		}  
		GUILayout.EndArea();  
		Handles.EndGUI();     
	}  
}  